﻿JsonTableBuilder = function () {
    //表示表名(或者表类型)
    var TableType = "";
    //数组.保存所有列名
    var Columns = new Array();

    ///<summary>
    ///根据列索引获取列名(Columns属性必须是有效的)
    ///</summary>
    function getColNameByColIndex(colIndex) {
        if (Columns.length == 0 || Columns == undefined)
            throw new Error; //抛出异常
        return Columns[colIndex];
    }

    ///	<summary>
    ///		根据表ID 获取包含表字段集合的行 
    ///	</summary>
    ///	<param name="value" type="String" optional="true"> 表名
    ///	</param>
    ///	<returns type="Array" />
    function getColNamesFrom(tableId) {
        var t = $(tableId);
        allColmns = new Array();
        $(tableId).find("tr").each(function (k) {
            if (k == 1)
                return false;
            $(this).find("td").each(function (i) {
                allColmns.push($(this).html());
            });
        });
        return allColmns;
    }

    var originalCols = "";
    this.toJsonData = function toJsonTableData(tableID) {
        //如果当前Columns 属性没有值 ,试着从目标表里面获取字段集合.
        //
        if (Columns.length == 0 || Columns == undefined) {
            Columns = getColNamesFrom(tableID);
        }
        var allRows = "";
        originalCols = getColumnsToJson();
        var rows = "{\"OriginalCols\":[" + originalCols + "],\"Rows\":[";
        $(tableID).find("tr").each(function (i) {
            if (i != 0) {
                var key = "{\"Key\":" + i + "," + "\"Value\":[";
                var inner = "";
                //alert($(this).html());
                $(this).find("td").each(function (c) {
                    inner += "{\"ColName\":\"" + Columns[c] + "\"," + "\"Value\":\"" + $(this).html() + "\"},";
                });
                inner = inner.substr(0, inner.length - 2) + "}]},";
                key += inner;
                allRows += key;
            }
        });
        allRows = rows + allRows.substr(0, allRows.length - 2) + "}],\"TableType\":\"" + TableType + "\"}";
        //alert(allRows);
        return allRows;
    }
    function getColumnsToJson() {
        var result = "";
        for (var i = 0; i < Columns.length; i++) {
            result += "\"" + Columns[i] + "\",";
        }
        result = result.substr(0, result.length - 1);
        return result;
    }

    //设置字段列表
    this.setColumns = function setCols(colsArr) {
        Columns = colsArr;
    }
    //设置表名
    this.setTableType = function setType(tableName) {
        TableType = tableName;
    }

    //对 string 的扩展 ,支持 string.format ;
    string = {};
    string.Format = function () {
        var param = [];
        for (var i = 0, length = arguments.length; i < length; i++) {
            param.push(arguments[i]);
        }
        var format = param[0];
        param.shift();
        return format.replace(/\{(\d+)}/g, function (m, i) {
            return param[i];
        });
    }
}